package business_logic;

import java.util.Map;
import java.util.TreeMap;

public class Konami {
	
	private static final int KEY_LEFT 	= 37;
    private static final int KEY_RIGHT 	= 39;
    private static final int KEY_UP 	= 38;
    private static final int KEY_DOWN 	= 40;
    private static final int KEY_B 		= 66;

    static private int[] code = 
        {KEY_UP, KEY_UP, KEY_DOWN, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_LEFT, KEY_RIGHT, KEY_B};
    static private Map<Integer, Integer>[] graph;
    static private int currentNode = 0;

    static { 
        graph = generateSequenceMap(code);
    }

    static public boolean checkKonami(int keyPressed) {
        Integer nextNode = graph[currentNode].get(keyPressed);
        //Set currentNode to nextNode or to 0 if no matching sub-sequence exists
        currentNode = (nextNode==null ? 0 : nextNode);

        return currentNode == code.length-1;
    }


    @SuppressWarnings("unchecked")
	static private Map<Integer, Integer>[] generateSequenceMap(int[] sequence) {

        //Create map
        Map<Integer, Integer>[] graph = new Map[sequence.length];
        for(int i=0 ; i<sequence.length ; i++) {
            graph[i] = new TreeMap<Integer,Integer>();
        }

        //i is delta
        for(int i=0 ; i<sequence.length ; i++) {
            loop: for(int j=i ; j<sequence.length-1 ; j++) {
            if(sequence[j-i] == sequence[j]) {
            	//Ensure that the longest possible sub-sequence is recognized
                Integer value = graph[j].get(sequence[j-i+1]);
                if(value == null || value < j-i+1)
                    graph[j].put(sequence[j-i+1], j-i+1);
            }
            else
                break loop;
            }
        }
        return graph;
    }
}